<?php

if (!function_exists('site_info')) {
    function site_info($type = 'name', $admin = false)
    {
        $ci = & get_instance();
        $info_list = array(
            'assets_url',
            'assets_url_raw',
            'template_url',
            'template_dir',
        );
        if (!in_array($type, $info_list))
            $type = 'assets_url';

        if (!$admin) {
            $theme_dir = 'themes/' . $ci->config->item('frontendTheme') . '/';
        } else {
            $theme_dir = APPPATH_RAW . '/themes/' . $ci->config->item('backendTheme') . '/';
        }
        switch ($type) {
            case 'assets_url' :
                $data = $ci->config->item('base_url') . $theme_dir . 'assets/';
                break;
            case 'assets_url_raw':
                $data = $theme_dir . 'assets/';
                break;
            case 'template_url' :
                $data = $ci->config->item('base_url') . $theme_dir;
                break;
            case 'template_dir' :
                $data = FCPATH . $theme_dir;
                break;
        }
        return $data;
    }
}


if (!function_exists('admin_url')) {
    function admin_url($str = '')
    {
        $str = trim($str, '/');
        return site_url(config_item('admin_folder') . '/' . $str);
    }
}

if (!function_exists('ws_password_hash')) {
    function ws_password_hash($password)
    {
        return sha1($password);
    }
}

if (!function_exists('get_gravatar')) {
    function get_gravatar($email, $s = 80, $d = 'mm', $r = 'g', $img = false, $atts = array())
    {
        $url = 'http://www.gravatar.com/avatar/';
        $url .= md5(strtolower(trim($email)));
        $url .= "?s=$s&d=$d&r=$r";
        if ($img) {
            $url = '<img src="' . $url . '"';
            foreach ($atts as $key => $val)
                $url .= ' ' . $key . '="' . $val . '"';
            $url .= ' />';
        }
        return $url;
    }
}

if (!function_exists('active_url')) {
    function active_url($url, $class = 'active', $full_length = false)
    {
        $url = strtolower($url);
        $CI = & get_instance();
        $css = '';
        $current_url = strtolower($CI->uri->uri_string);
        if (!$current_url && $url == 'home')
            return $class;
        if ($full_length && $current_url == $url)
            $css = $class;
        else if (substr($current_url, 0, strlen($url)) == $url && !$full_length) {
            $css = $class;
        }
        return $css;
    }
}
if (!function_exists('array_pluck')) {
    function array_pluck($key, $input)
    {
        if (is_array($key) || !is_array($input)) return array();
        $array = array();
        foreach ($input as $v) {
            $v = (array)$v;
            if (array_key_exists($key, $v)) $array[] = $v[$key];
        }
        return $array;
    }
}
if (!function_exists('getAspectRatio')) {
    function getAspectRatio($w, $h)
    {
        $rem = false;
        $newW = $w;
        $newH = $h;

        while ($h != 0) {
            $rem = $w % $h;
            $w = $h;
            $h = $rem;
        }

        $newH = $newH / $w;
        $newW = $newW / $w;
        return array($newW, $newH);
    }
}

if (!function_exists('GetImageInfo_')) {
    function GetImageInfo_($path, $method = 'default')
    {
        $width = $height = false;
        switch ($method) {
            case 'http_Curl':
                $headers = array(
                    "Range: bytes=0-32768"
                );
                $curl = curl_init($path);
                curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
                $data = curl_exec($curl);
                curl_close($curl);
                $im = @imagecreatefromstring($data);
                $width = @imagesx($im);
                $height = @imagesy($im);
                break;
            case 'default':
                list($width, $height) = getimagesize($path);
                break;
        }

        return array('width' => $width, 'height' => $height, 'pathInfo' => pathinfo($path));
    }
}


if (!function_exists('build_slug')) {
    function build_slug($str)
    {
        return url_title(convert_accented_characters($str), '-', true);
    }
}

if (!function_exists('cleanImageName')) {
    function cleanImageName($str)
    {
        //$image_name = preg_replace('/[^A-Z\s\d\']/im', ' ', $str);
        $image_name = preg_replace('/\s+/im', ' ', $str);
        $doNotCapitalize = array("a", "an", "and", "as", "at", "but", "by", "etc", "for", "in", "into", "is", "nor", "of", "off", "on", "onto", "or", "so", "the", "to", "unto", "via");
        $image_name_arr = explode(' ', $image_name);
        $final = '';
        foreach ($image_name_arr as $k => $text) {
            if ($k > 0) {
                $final .= ' ';
            }
            if ($k == 0 || !in_array($text, $doNotCapitalize))
                $final .= ucfirst($text);
            else $final .= $text;
        }
        return trim($final);
    }
}

if (!function_exists('calc_image_res')) {
    function calc_image_res($width, $height, $img_width, $img_height)
    {
        $ratio = $img_width / $img_height;

        $not_match = false;

        if ($img_width > $img_height) {
            $return_width = round($height * $ratio);
            $return_height = $height;
            if ($return_width < $width)
                $not_match = true;
        }

        if ($not_match || $img_width < $img_height) {
            $return_width = $width;
            $return_height = round($width / $ratio);
        }

        if ($ratio == 1) {
            $highest_size = 0;
            if ($width == $height)
                $highest_size = $width;
            elseif ($width > $height)
                $highest_size = $width;
            else $highest_size = $height;
            $return_width = $highest_size;
            $return_height = $highest_size;
        }

        return array(
            'ratio' => $ratio,
            'required_width' => $width,
            'required_height' => $height,
            'width' => $return_width,
            'height' => $return_height
        );
    }
}

if (!function_exists('bad_words_list')) {
    function bad_words_list()
    {
        $words = config_item('bad_words');
        $words = array_filter(explode(',', $words));
        usort($words, function ($a, $b) {
            return strlen($b) - strlen($a);
        });
        return $words;
    }
}

if (!function_exists('ws_load_content')) {
    function ws_load_content($file, $variables = array(), $extend = true)
    {
        $ci = & get_instance();
        if (!empty($variables) && $extend) {
            foreach ($variables as $k => $v) {
                $ci->tpl->$k = $v;
            }
        }
        return $ci->tpl->fetch($file, $extend ? $ci->tpl->get_DataVar() : $variables);
    }
}

if (!function_exists('custom_404')) {
    function custom_404($status = 404)
    {
        $CI = & get_instance();
        $CI->output->set_status_header($status);
        $data = array();
        $CI->tpl->meta ['title'] = '404 Not found';
        $CI->tpl->contents ['404'] = $CI->tpl->fetch('contents/error_404', $data);
        echo $CI->tpl->render('layouts/default', true, true);
        exit;
    }
}
if (!function_exists('foldersize')) {
    function foldersize($dir)
    {
        $count_size = 0;
        $count = 0;
        if (!is_dir($dir))
            return false;
        $dir_array = scandir($dir);
        foreach ($dir_array as $key => $filename) {
            if ($filename != ".." && $filename != ".") {
                if (is_dir($dir . "/" . $filename)) {
                    $new_foldersize = foldersize($dir . "/" . $filename);
                    $count_size = $count_size + $new_foldersize;
                } else if (is_file($dir . "/" . $filename)) {
                    $count_size = $count_size + filesize($dir . "/" . $filename);
                    $count++;
                }
            }

        }
        return $count_size;
    }
}
if (!function_exists('delete_md5')) {
    function delete_md5($md5 = array(), $cache_folder = '')
    {
        if (!is_array($md5))
            $md5 = array($md5);

        if (empty($md5))
            return false;
        $CI = & get_instance();
        $cache_root_folder = dirname($CI->db->cachedir) . '/';
        $scan_folder = $cache_root_folder;
        if ($cache_folder)
            $scan_folder .= ltrim($cache_folder, '/');
        $matches = match_fileNames($scan_folder, $md5);
        if ($matches) {
            array_map("unlink", $matches);
        }
    }
}

if (!function_exists('match_fileNames')) {
    function match_fileNames($source_dir, $matches)
    {
        static $_fileData = array();

        if ($fp = @opendir($source_dir)) {
            while (FALSE !== ($file = readdir($fp))) {
                if (@is_dir($source_dir . $file) && strncmp($file, '.', 1) !== 0) {
                    match_filenames($source_dir . $file . DIRECTORY_SEPARATOR, $matches);
                } elseif (strncmp($file, '.', 1) !== 0) {
                    if (in_array($file, $matches))
                        $_fileData[] = $source_dir . $file;
                }
            }
            return $_fileData;
        } else {
            return FALSE;
        }
    }
}

if (!function_exists('rating_block')) {
    function rating_block($vote_up, $vote_down, $NumberOfStars = 5, $return_count = false)
    {
        $total_vote = $vote_up + $vote_down;
        $color_stars = 0;
        if ($total_vote)
            $color_stars = (($vote_up / $total_vote) * 100) / (100 / $NumberOfStars);
        if ($return_count)
            return $color_stars;
        $explode = explode('.', $color_stars);
        $i = 0;
        $output = '';
        if ($explode[0]) {
            foreach (range(1, $explode[0]) as $fullstar) {
                $output .= '<i class="fa fa-star"></i>';
                $i++;
            }
        }
        if (isset($explode[1])) {
            $output .= '<i class="fa fa-star-half-empty"></i>';
            $i++;
        }
        if ($i < $NumberOfStars) {
            foreach (range(1, $NumberOfStars - $i) as $emptyStar) {
                $output .= '<i class="fa fa-star-o"></i>';
            }
        }
        return $output;
    }
}

if (!function_exists('download_file')) {
    function download_file($url, $save_path, $source = false, $return = false)
    {
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1");
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_REFERER, ($source ? $source : $url));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
        $raw = curl_exec($curl);
        curl_close($curl);
        if ($return)
            return $raw;
        $fp = fopen($save_path, 'w');
        fwrite($fp, $raw);
        fclose($fp);
        return true;
    }
}

if (!function_exists('clean_data')) {
    function clean_data($data)
    {
        $data = preg_replace('/\s+/', ' ', $data);
        $data = preg_replace('/>\s</', '><', $data);
        $data = preg_replace('/\s+"/', '"', $data);

        return trim($data);
    }
}

spl_autoload_register(function ($class) {
    $prefix = 'Facebook\\';
    $base_dir = defined('FACEBOOK_SDK_V4_SRC_DIR') ? FACEBOOK_SDK_V4_SRC_DIR : APPPATH . 'libraries/Facebook/';

    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        return;
    }

    $relative_class = substr($class, $len);
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';

    if (file_exists($file)) {
        require $file;
    }
});


function facebook_permissions()
{
    return array('email,publish_actions');
}

function url_title_no_space($str, $separator = '-', $lowercase = FALSE)
{
    if ($separator === 'dash')
    {
        $separator = '-';
    }
    elseif ($separator === 'underscore')
    {
        $separator = '_';
    }

    $q_separator = preg_quote($separator, '#');

    $trans = array(
        '&.+?;'			=> '',
        '\s+'			=> $separator,
        '('.$q_separator.')+'	=> $separator
    );

    $str = strip_tags($str);
    foreach ($trans as $key => $val)
    {
        $str = preg_replace('#'.$key.'#i', $val, $str);
    }

    if ($lowercase === TRUE)
    {
        $str = strtolower($str);
    }

    return trim(trim($str, $separator));
}